#!/usr/bin/env bash
set -e

_thisdir="$( cd "$( dirname "$0" )" && pwd )"
_build="${_thisdir}/_build"
_ifwroot="${_build}/qt-ifw"
_date=$(date +'%Y%m%d')
_dateqif=$(date +'%Y-%m-%d')
_version="${_date}"
_newmsysbase="${_build}/newmsys"
_newmsys="${_newmsysbase}/msys64"
_arch_name="x86_64"
_tarfile="${_thisdir}/msys2-base-${_arch_name}-${_date}.tar"

create_archives() {
  echo "[Creating tarball...]"
  pushd "${_newmsys}" > /dev/null
    /usr/bin/tar --transform='s/:/_/g' --dereference --hard-dereference -cf "${_tarfile}" *
  popd > /dev/null

  echo "[Creating zstd archive...]"
  zstd -T0 -22 --ultra --force "${_tarfile}" -o "${_tarfile}.zst"
  zstd --test "${_tarfile}.zst"

  rm "${_tarfile}"
}

create_sfx() {
  echo "[Creating SFX...]"

  pushd "${_newmsysbase}" > /dev/null
    "${_thisdir}/create-sfx.sh" "${_tarfile}.zst" "${_thisdir}/msys2-base-${_arch_name}-${_date}.sfx.exe"
  popd > /dev/null
}

create_chroot_system() {
  echo "[Creating chroot system...]"
  rm -Rf "${_newmsysbase}" && mkdir -p "${_newmsys}"

  pushd "${_newmsys}" > /dev/null
    mkdir -p var/lib/pacman
    mkdir -p var/log
    mkdir -p tmp

    pacman -Syu --root "${_newmsys}"
    pacman -S filesystem msys2-runtime --noconfirm --root "${_newmsys}"
    pacman -S base --noconfirm --root "${_newmsys}"
    . "${_thisdir}/install-application"
  popd > /dev/null
}

main() {
  pacman -S --noconfirm --needed \
    "git" \
    "curl" \
    "unzip" \
    "${MINGW_PACKAGE_PREFIX}-7zip" \

  create_chroot_system
  create_archives
  create_sfx
}

main